# -*- coding: utf-8 -*-
import sys
sys.path.append('../')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
import requests
from common.helper import Helper
from urllib.parse import urlencode



class Spider(object):
    def __init__(self):
        self.mysql = MysqlClient()
        self.name = "合众新爱无忧特定恶性肿瘤疾病保险"
    # 生成产品数据
    def genProductInfo(self):
        plan = {

            "planA":{
                # 年龄段
                "year":[str(i) for i in range(0,51)],
                # 性别
                "gender":["M","F"],
                # 保额
                "money":["10000","20000","30000","40000","50000","100000"],
                #保障期限
                "expire":["终身"],
                #缴费间隔
                "interval":["5","10","20"],
                #缴费方式
                "payType":["年缴"]
            },
            "planB": {
                # 年龄段
                "year": [str(i) for i in range(51, 61)],
                # 性别
                "gender": ["M", "F"],
                # 保额
                "money": ["10000", "20000", "30000", "40000", "50000", "100000"],
                # 保障期限
                "expire": ["终身"],
                # 缴费间隔
                "interval": ["5", "10"],
                # 缴费方式
                "payType": ["年缴"]
            },

        }
        for k in plan:
            for v in product(plan[k]["year"],plan[k]["gender"],plan[k]["money"],plan[k]["expire"],plan[k]["interval"],plan[k]["payType"]):

                self.mysql.cursor.execute(domain[self.name]["insert_sql"].format(
                    v[0],v[1],v[2],v[3],v[4],v[5]
                ))
                self.mysql._conn.commit()
                print( domain[self.name]["insert_sql"].format(
                    v[0],v[1],v[2],v[3],v[4],v[5]
                ))

    #执行爬虫
    def requestJson(self,dt=None):

        data = {
            "json":'{"id":"insurant.0.jobCode","value":"1101001"},{"id":"productId","value":"4019"},{"id":"holder.0.certiCompose","value":"1::'+str(2020-int(dt["year"]))+'-01-01:'+dt["gender"]+'"},{"id":"product.0.401901.amount","value":"'+dt["money"]+'"},{"id":"product.0.coverage","value":"1_0"},{"id":"product.0.charge","value":"1_2_'+dt["interval"]+'"},',
            "productId":"4019"
        }

        payload = urlencode( data )

        r = requests.post( url = domain[self.name]["url"],headers=domain[self.name]["header"],data=payload)

        print( r.text )
        if r.status_code == 200 and "保费测算失败!" not in r.text:

            price = Helper.decimalParse( r.json()["sumPrem"])

            data = {
                "name":self.name,
                "id":dt["id"],
                "price":price
            }
            self.mysql.updatePrice( data )

        else:

            # 任务执行失败
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 3
            }
            print("/*产品价格更新失败:%d*/" % dt["id"])
            self.mysql.updateTask(data)

    def main(self):

        while True:

            # 随机领取一条数据
            dt = self.mysql.randTask(self.name)

            if not dt:
                print("产品价格抓取完成~~~")

                return

                # 任务执行状态
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 1
            }

            self.mysql.updateTask(data)

            self.requestJson(dt)

